﻿using System.Net;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;
using NewLife.Serialization;
using PMS.WebApi.Models;

namespace PMS.WebApi.Utils
{
    public class ApiAuthorize : AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            return true;
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //url获取token
            var request = actionContext.Request ?? new HttpRequestMessage();
            var content = request.Properties["MS_HttpContext"] as HttpContext;
            var token = content.Request.Headers["Access-Token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                string router = content.Request.Path;
                if (
                    token.Equals(EncryptHelper.MD5Encrypt(router), StringComparison.InvariantCultureIgnoreCase) ||
                    token.Equals(EncryptHelper.MD5Encrypt(router.ToLower()), StringComparison.InvariantCultureIgnoreCase) ||
                    EncryptHelper.DESDecrypt(token).Equals(router, StringComparison.InvariantCultureIgnoreCase))
                {
                    base.IsAuthorized(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
            else
            {
                var attributes =
                    actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous)
                {
                    base.OnAuthorization(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);

            var response = actionContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.Forbidden;
            var content = new ResultMsg
            {
                success = false,
                message = "服务端拒绝访问：您没有权限或者网络异常！"
            };
            response.Content = new StringContent(content.ToJson(), Encoding.UTF8, "application/json");
        }
    }
}
